package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hsl
 * @CreateTime: 2025-03-03  15:49
 */
@Component
public class TrackReceiver {

    @Resource
    private TrackInfoService trackInfoService;

    @Resource
    private RedisTemplate redisTemplate;
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateTrackStat(String content, Message message, Channel channel) {
        // 判断消息是否正确过来
        if (!StringUtils.isEmpty(content)){
            // 消息类型属于trackStatMqVo实体
            TrackStatMqVo trackStatMqVo = JSONObject.parseObject(content, TrackStatMqVo.class);
            // 使用businessNo进行去重 防止重复消费  redis setnx进行解决
            String businessNo = trackStatMqVo.getBusinessNo();
            Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("trackStat:" + businessNo, businessNo, 10, TimeUnit.MINUTES);
            // 判断 是否重复消费
            if (ifAbsent){
                // 调用服务层方法更新数据
                try {
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    //  发生异常后将redis缓存中的"trackStat:" + businessNo进行删除  防止后续请求无法进行消费
                    redisTemplate.delete("trackStat:" + businessNo);
                    throw new RuntimeException(e);
                }
            }
        }
        // 手动确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
